package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.Connect;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Service {
    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = Connect.createConnection();

        Channel channel = connection.createChannel();

        // 这里需要声明两个 请求队列没有的话就传不到对应的目标 响应队列没有的话就会报错
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE, false, false, false, null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE, false, false, false, null);

        // 处理请求队列中的消息 如果正确 那么就将处理后的消息放入响应队列
        channel.basicQos(1); // 设置最多同时收到一个
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String request = new String(body);
                System.out.println("接受到请求消息：" + request);
                AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                // 传给响应队列
                channel.basicPublish("", properties.getReplyTo(), props, body);
                // 手动确定
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        channel.basicConsume(Constants.RPC_REQUEST_QUEUE, false ,consumer);
    }
}
